#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   Music
@Time    :   2023/03/16 09:37:16
@author  :   Eval
@Version :   1.0
@Describe:   游戏音效管理
'''
import pygame
from os import listdir as OS_Listdir,path as OS_PATH
from conf.GameLogin import *
from lib.scripts.GC import *

class Music:
    def __init__(self,parent) -> None:
        import main
        self.parent:main.Run = parent
        pygame.mixer.init()  # 初始化混合器
        # 存储所有加载的音效名, 音效名称:音效对象
        self.__sounds:dict[pygame.mixer.Sound] = {}
        self.__isPlaySound = False  # 是否允许播放音效
        # 加载 sounds 目录下的所有音效
        path = "lib\sounds\\"
        if OS_PATH.exists(path):
            files = OS_Listdir(path)
            for f in files:
                try:
                    self.parent.GameLoad.tips = f"加载音效:{f} 完成"
                    self.__sounds[f] = pygame.mixer.Sound(path+f)
                    # 设置默认音量
                    self.__sounds[f].set_volume(0.2)
                except:
                    print_error(f"无法识别的音效:{f}")
        else:
            self.parent.GameLoad.tips = f"无法找到路径为:{path} 游戏音效"
            print_error(f"无法找到路径为:{path} 游戏音效")

        # # 加载背景音乐
        bgmPath = "lib\\bgms\startText.mp3"
        if OS_PATH.exists(bgmPath):
            pygame.mixer.music.load(bgmPath)
            pygame.mixer.music.set_volume(0.05)
        else:
            print_error(f"无法找到路径为: {bgmPath} 的游戏背景音乐")

    def _load(self):
        # 播放bgm
        pygame.mixer.music.play(-1)
        # 判断全局配置中是否默认停止音乐
        if not GC.GC_GlobalScripts["BGMState"]:
            pygame.mixer.music.pause()
    
    def PlaySound(self,soundName:str,volume:float=0.2):
        """播放音效"""
        if not self.__isPlaySound:
            return
        sound:pygame.mixer.Sound = self.__sounds.get(soundName)
        if sound is None:
            print_error(f"播放音效:{soundName} 失败,无法播放不存在的音效")
            return
        if sound.get_volume() != volume:
            # 设置音量
            sound.set_volume(volume)
        sound.play()


    def ModifyPlayBGM(self):
        """播放背景音乐"""
        if pygame.mixer.music.get_busy():
            # 暂停
            pygame.mixer.music.pause()
            return
        pygame.mixer.music.unpause()


    def ModifyPlaySound(self):
        """改变是否允许播放音效状态"""
        self.__isPlaySound = not self.__isPlaySound

    def isPlaySound(self) -> str:
        """获取游戏音效的状态文本"""
        return "关闭" if not self.__isPlaySound else "开启"

    def isPlayBGM(self) -> str:
        """获取bgm的播放状态"""
        return "暂停" if not pygame.mixer.music.get_busy() else "播放"

    def __str__(self) -> str:
        return f"游戏音乐管理模块:音效数量:{len(self.__sounds.keys())}"